package com.bbs.core.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bbs.core.common.WebUtils;
import com.bbs.core.model.Reply;
import com.bbs.core.model.Topic;
import com.bbs.core.model.User;
import com.bbs.core.service.MessageService;
import com.bbs.core.service.ReplyService;
import com.bbs.core.service.TopicService;

@Controller
public class ReplyController {
	
	@Autowired
	private WebUtils webUtils;
	
	@Autowired
	private ReplyService replyService;
	
	@Autowired
	private TopicService topicService;
	
	@Autowired
	private MessageService messageService;
	
	/**
	 * 回复评论改为Ajax方式提升体验
	 * @param reply
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@PostMapping("/bbs/reply/save")
	public JSONObject saveReply(Reply reply, HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject result = new JSONObject();
		result.put("err", 1);
		User user = webUtils.currentUser(request, response);
		if(user==null){
			result.put("msg", "未登录用户！");
		}else if(reply.getContent().length()<2){
			result.put("msg", "回复内容太短，请修改!");
		}else{
			reply.setUserId(user.getId());
			reply.setPostId(reply.getPostId());
			reply.setCreateTime(new Date());
			replyService.saveReply(reply);
			reply.setUser(user);
			result.put("msg", "评论成功！");
			result.put("err", 0);
			
			Topic topic = topicService.getTopicByPrimaryKey(reply.getTopicId());			
			messageService.notifyParticipant(reply.getTopicId(),user.getId());
			
		}
		return result;
	}

}
